<template>
  <a-card>
    <div class="operator">
      <a-button @click="addNew" type="primary">新建</a-button>
    </div>

    <a-table
      bordered
      :columns="columns"
      :data-source="dataSource"
      :loading="spinning"
      @change="handleTableChange"
      :pagination="pagination"
    >
      <div slot="action" slot-scope="record">
        <a style="margin-right: 8px" @click="editRole(record)">
          <a-icon type="edit" />编辑
        </a>
        <a @click="deleteRecord(record)"> <a-icon type="delete" />删除 </a>
      </div>

      <p slot="expandedRowRender" slot-scope="record" style="margin: 0">
        <span>User_Parameter</span>
        <pre>{{ record.User_Parameter }}</pre>
      </p>
    </a-table>

    <a-drawer
      :title="drawertitle"
      :width="600"
      :visible="visible"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
    >
      <a-form :form="form" layout="vertical" @submit="handleSubmit">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="名称">
              <a-input
                v-decorator="[
                  'name',
                  {
                    rules: [
                      { required: true, message: 'Please enter user name' },
                    ],
                  },
                ]"
                placeholder="Please enter user name"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="登录名">
              <a-input
                v-decorator="[
                  'loginname',
                  {
                    rules: [
                      {
                        required: true,
                        message: 'Please enter user login name',
                      },
                    ],
                  },
                ]"
                placeholder="Please enter user login name"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="登录密码">
              <a-input
                v-decorator="[
                  'password',
                  {
                    rules: [
                      {
                        required: true,
                        message: 'Please enter user login password',
                      },
                    ],
                  },
                ]"
                placeholder="Please enter user login password"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="角色">
              <a-select
                v-decorator="[
                  'role',
                  {
                    rules: [
                      { required: true, message: 'Please choose the role' },
                    ],
                  },
                ]"
                placeholder="Please choose the role"
              >
                <a-select-option
                  v-for="(item, index) in roleOptions"
                  :value="item.Role_ID"
                  :key="index"
                >
                  {{ item.Role_Name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="描述">
              <a-textarea
                v-decorator="['User_Parameter']"
                :rows="4"
                placeholder="please enter user parameter"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <div
          :style="{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
            zIndex: 1,
          }"
        >
          <a-button :style="{ marginRight: '8px' }" @click="onClose">
            Cancel
          </a-button>
          <a-button type="primary" html-type="submit">
            Submit
          </a-button>
        </div>
      </a-form>
    </a-drawer>
  </a-card>
</template>

<script>

const columns = [
  {
    title: "编号",
    dataIndex: "User_ID",
  },
  {
    title: "名称",
    dataIndex: "User_Name",
  },
  {
    title: "登录名",
    dataIndex: "User_LoginName",
  },
  {
    title: "登录密码",
    dataIndex: "User_Pwd",
  },
  {
    title: "角色",
    dataIndex: "User_RoleName",
  },
  {
    title: "是否删除",
    dataIndex: "User_IsDelete",
  },
  {
    title: "创建时间",
    dataIndex: "User_CreateTime",
    sorter: true,
  },
  {
    title: "操作",
    scopedSlots: { customRender: "action" },
  },
];

export default {
  data() {
    return {
      advanced: true,

      visible: false,
      selectRow: null,

      dataSource: [],
      roleOptions: [],

      form: this.$form.createForm(this),
      drawertitle: "添加用户",

      spinning: false,
      pagination: {
        total: 20,
        title: "",
        tableName: "",
      },
      columns: columns,
    };
  },

  created: function() {
    this.loadTable("iToolBase", "Sys_User");
    this.loadRoleInfo("iToolBase", "Sys_Role");
  },

  methods: {
    deleteRecord(row) {
      console.log(row);
      var that = this;
      this.$confirm({
        title: "Are you sure delete this user?",
        content: "删除后将从用户列表中移除",
        okText: "Yes",
        okType: "danger",
        cancelText: "No",
        onOk() {
          that.$cloud
            .invokeApiJson(
              "iToolBase",
              JSON.stringify({
                Sys_User: {
                  User_ID: row.User_ID,
                },
              }),
              "remove"
            )
            .then((res) => {
              res = typeof res == "string" ? JSON.parse(res) : res;
              console.log(res);
              if (res.code == 200) {
                that.$message.success("删除成功");
                that.dataSource = that.dataSource.filter(
                  (item) => item.User_ID !== row.User_ID
                );
              } else {
                that.$message.error("发生错误：" + res.info);
              }
            })
            .catch((error) => {
              console.log(error);
              that.$message.error("发生错误：" + error);
            });
        },
        onCancel() {},
      });
    },

    handleTableChange(p, filters, sorter) {
      console.log(p, filters, sorter);
      this.loadTable(
        this.pagination.title,
        this.pagination.tableName,
        p.current,
        sorter.field,
        (sorter.order || "").replace("end", "")
      );
    },

    addNew() {
      this.drawertitle = "添加用户";
      this.visible = true;
      setTimeout(
        function() {
          this.form.setFieldsValue({
            name: "",
            loginname: "",
            password: "",
          });
        }.bind(this),
        200
      );
    },

    editRole(row) {
      this.selectRow = row;
      this.drawertitle = "编辑用户";
      this.visible = true;
      setTimeout(
        function() {
          this.form.setFieldsValue({
            name: row.User_Name,
            loginname: row.User_LoginName,
            password: row.User_Pwd,
            role: row.User_RoleID - 0,
            User_Parameter: row.User_Parameter
          });
        }.bind(this),
        200
      );
    },

    onClose() {
      this.visible = false;
      this.selectRow = null;
    },

    handleSubmit(e) {
      e.preventDefault();
      var that = this;
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);

          if (!values.role) {
            that.$message.error("Please choose the role");
            return;
          }

          var json = {
            Sys_User: {
              User_Name: values.name,
              User_LoginName: values.loginname,
              User_Pwd: values.password,
              User_Parameter: values.User_Parameter
            },
          };

          if (that.selectRow != null) {
            json.Sys_User.User_ID = that.selectRow.User_ID;
          } else {
            json.Sys_User.User_IsDelete = 0;
            json.Sys_User.User_CreateTime = new Date().Format(
              "yyyy-MM-dd HH:mm:ss"
            );
          }

          console.log(json);

          that.$cloud
            .invokeApiJson(
              "iToolBase",
              JSON.stringify(json),
              this.selectRow == null ? "register" : "modify"
            )
            .then((res) => {
              console.log(res);
              res = typeof res == "string" ? JSON.parse(res) : res;
              var userid = 0;
              //TODU Role
              if (res.code == 200) {
                // 添加用户
                if (this.selectRow == null) {
                  userid = res.Sys_User.date;
                  that.dataSource.push({
                    key: res.Sys_User.date,
                    User_ID: res.Sys_User.date,
                    User_Name: values.name,
                    User_LoginName: values.loginname,
                    User_Pwd: values.password,
                    User_IsDelete: 0,
                    User_Parameter: values.User_Parameter,
                    User_CreateTime: new Date().Format("yyyy-MM-dd HH:mm:ss"),
                  });
                }
                // 修改用户
                else {
                  for (let index = 0; index < that.dataSource.length; index++) {
                    const element = that.dataSource[index];
                    if (element.User_ID == that.selectRow.User_ID) {
                      userid = that.selectRow.User_ID;
                      element.User_Name = values.name;
                      element.User_LoginName = values.loginname;
                      element.User_Pwd = values.password;
                      element.User_Parameter = values.User_Parameter;
                    }
                  }
                }

                if (this.selectRow == null) {
                  // 添加角色
                  that.handleUserRole(userid, values.role, 0);
                } else {
                  if (this.selectRow.User_RoleID) {
                    console.log(this.selectRow)
                    // 修改角色
                    if (values.role != this.selectRow.User_RoleID - 0)
                      that.handleUserRole(
                        userid,
                        values.role,
                        this.selectRow.User_UserRoleID
                      );
                  } else {
                    // 添加角色
                    that.handleUserRole(userid, values.role, 0);
                  }
                }

                that.$message.success(
                  this.selectRow == null ? "添加成功" : "修改成功"
                );
              } else {
                that.$message.error("发生错误：" + res.msg);
              }
              that.onClose();
            })
            .catch((error) => {
              that.$message.error("发生错误：" + error);
              console.log(error);
            });
        }
      });
    },

    handleUserRole(UserID, RoleID, UserRoleID) {
      var that = this;

      var json = {
        Sys_UserRole: {
          UserRole_UserID: UserID,
          UserRole_RoleID: RoleID,
        },
      };

      if (UserRoleID == 0) {
        json.Sys_UserRole.UserRole_CreateTime = new Date().Format(
          "yyyy-MM-dd HH:mm:ss"
        );
      } else {
        json.Sys_UserRole.UserRole_ID = UserRoleID;
      }

      that.$cloud
        .invokeApiJson(
          "iToolBase",
          JSON.stringify(json),
          UserRoleID == 0 ? "register" : "modify"
        )
        .then((res) => {
          console.log(res);
          res = typeof res == "string" ? JSON.parse(res) : res;
          if (res.code == 200 & res.Sys_UserRole.date > 0) {
            for (let index = 0; index < that.dataSource.length; index++) {
              const element = that.dataSource[index];
              if (element.User_ID == UserID) {

                element.User_RoleID = RoleID;
                element.User_RoleName = that.roleOptions.filter(
                  (item) => item.Role_ID == RoleID
                )[0].Role_Name;

                if (UserRoleID == 0) {
                  element.User_UserRoleID = res.Sys_UserRole.date;
                }
                
              }
            }
          } else {
            console.log(json)
            that.$message.error("修改角色失败，请重试");
          }
        })
        .catch((error) => {
          that.$message.error("发生错误：" + error);
          console.log(error);
        });
    },

    loadTable(title, tableName, page, field, orderby) {
      this.spinning = true;

      this.pagination.title = title;
      this.pagination.tableName = tableName;

      var script = {};

      // script["[]"] = {
      //   count: 12,
      //   page: page ? page : 1,
      //   query: 2,
      // };

      // 关联查询
      script["[]"] = {
        Sys_User: {},
        Sys_UserRole: {
          "UserRole_UserID@": "/Sys_User/User_ID",
          "@column": "UserRole_RoleID,UserRole_ID",
        },
        Sys_Role: {
          "Role_ID@": "/Sys_UserRole/UserRole_RoleID",
          "@column": "Role_ID,Role_Name",
        },
      };

      if (field) {
        script["[]"][tableName]["@order"] =
          orderby == "asc" ? field + "+" : field + "-";
      }

      script["total@"] = "/[]/total";

      console.log(script);

      this.$cloud
        .invokeApiJson("iToolBase", JSON.stringify(script), "get")
        .then((res) => {
          var data = JSON.parse(res);
          this.spinning = false;
          var tableData = data["[]"];
          this.dataSource = [];

          console.log(tableData);

          this.pagination.total = data.total;
          this.pagination["show-total"] = (total, range) =>
            `${range[0]}-${range[1]} of ${total} items`;
          this.pagination["pageSize"] = 12;
          this.pagination["defaultCurrent"] = 1;

          for (let index = 0; index < tableData.length; index++) {
            const row = tableData[index];
            row[tableName].key = row[tableName].User_ID;

            if (row.Sys_Role) {
              row[tableName].User_RoleID = row.Sys_UserRole.UserRole_RoleID;
              row[tableName].User_RoleName = row.Sys_Role.Role_Name;
              row[tableName].User_UserRoleID = row.Sys_UserRole.UserRole_ID;
            }else{
              if (row.Sys_UserRole) {
                row[tableName].User_UserRoleID = row.Sys_UserRole.UserRole_ID;
              }
              row[tableName].User_RoleID = null;
              row[tableName].User_RoleName = null;
            }

            this.dataSource.push(row[tableName]);
          }


          console.log(this.dataSource)
        });
    },

    loadRoleInfo(title, tableName) {
      this.spinning = true;

      this.pagination.title = title;
      this.pagination.tableName = tableName;

      var script = {};

      script["[]"] = {};

      script["[]"][tableName] = {};

      this.$cloud
        .invokeApiJson("iToolBase", JSON.stringify(script), "get")
        .then((res) => {
          var data = JSON.parse(res);
          this.spinning = false;
          var tableData = data["[]"];
          this.roleOptions = [];
          for (let index = 0; index < tableData.length; index++) {
            const row = tableData[index];
            this.roleOptions.push(row.Sys_Role);
          }
        });
    },
  },
};
</script>

<style lang="less" scoped>
.search {
  margin-bottom: 54px;
}
.fold {
  width: calc(100% - 216px);
  display: inline-block;
}
.operator {
  margin-bottom: 18px;
}

.operator button {
  margin-right: 18px;
}

@media screen and (max-width: 900px) {
  .fold {
    width: 100%;
  }
}
</style>
